﻿using System;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace OpcUaHelper
{
    /// <summary>
    /// 邮件处理Helper
    /// </summary>
    public static class EmailHelper
    {
        #region 发送邮件

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="Title">标题</param>
        /// <param name="Content">正文</param>
        /// <param name="AttachmentPath">附件地址</param>
        /// <param name="ReceiveEmail">接收人邮箱</param>
        /// <param name="FromEmail">发件人邮箱</param>
        /// <param name="FromName">发件人姓名</param>
        /// <param name="FromPassword">发件人邮箱授权码</param>
        /// <returns>成功或失败</returns>
        public static bool SendEmail(string Title, string Content, string AttachmentPath, string ReceiveEmail, string FromEmail, string FromName, string FromPassword)
        {
            try
            {
                #region 初始化邮件内容

                // 创建 MailMessage 对象并设置相关属性
                MailMessage mail = new MailMessage();

                // 添加邮件收件人地址, 可以添加多个接收邮箱地址
                mail.To.Add(ReceiveEmail);
                // mail.To.Add("email2@example.com);

                // 添加抄送人, 抄送同样可以添加多个
                //mail.CC.Add("emailcc@exmaple.com");

                // 设置发件人地址，发件人姓名，以及编码
                mail.From = new MailAddress(FromEmail, FromName, Encoding.UTF8);

                // 设置邮件标题
                mail.Subject = Title;

                // 邮件标题编码
                mail.SubjectEncoding = Encoding.UTF8;

                // 设置邮件正文内容
                mail.Body = Content;

                // 邮件正文内容的编码
                mail.BodyEncoding = Encoding.UTF8;

                // 设置邮件是否为HTML邮件
                mail.IsBodyHtml = false;

                // 设置邮件优先级
                mail.Priority = MailPriority.Normal;

                // 添加附件
                if (!string.IsNullOrEmpty(AttachmentPath))
                {
                    mail.Attachments.Add(new Attachment(AttachmentPath));
                }

                #endregion

                // 设置 SMTP 邮箱服务器服务器使用的地址、端口号等信息
                SmtpClient smtp = new SmtpClient("smtp.163.com", 25)
                {
                    // 设置发件人的邮箱和授权码。相当于登录邮箱
                    Credentials = new NetworkCredential(FromEmail, FromPassword)
                };

                // 发送邮件
                smtp.Send(mail);

                Console.WriteLine("邮件已成功发送！");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发送邮件时出错：{ex}");
                return false;
            }
        }

        #endregion

    }
}
